﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using deviceManage.Models;
using deviceManage.vo;
using deviceManage.Filters;


namespace deviceManage.Controllers
{
    /// <summary>
    /// 采购合同管理
    /// </summary>
    [CheckLoginAttribute]
    public class BuyContractController : Controller
    {
        private readonly DeviceCtx _context;

        public BuyContractController(DeviceCtx context)
        {
            _context = context;
        }

        //列表主页
        public IActionResult Index()
        {
            int? flag = HttpContext.Session.GetInt32("viewFlag");
            return View(Tuple.Create( flag));
        }

        //ajax 获取分页数据
        public AjaxResult List(int page, int limit, String name)
        {     

            AjaxResult r = new AjaxResult();
            r.Count = _context.BuyContract.Where(p => p.Deleted == 0).Count();
            r.Code = 0;
            try
            { 
                r.Data = _context.BuyContract.Include(p => p.DeviceType)
                .Where(p => p.Deleted == 0 && ((name == null) || p.Title.Contains(name)))
                .OrderByDescending(p => p.CreateDate)
                .Skip((page - 1) * limit).Take(limit) 
                .ToList(); 

            }  
            catch(Exception e)
            {
                r.Msg = e.Message;
            }


            return r;
        }


        /// <summary>
        /// 进入创建页面或者编辑页面
        /// </summary>
        public IActionResult Edit(String id)
        {
            //获取设备分类，用于下拉显示
            var typeList = _context.DeviceType.Where(p => p.Deleted == 0).OrderBy(p => p.SortOrder).ToList();

            //获取model
            BuyContract contract = new BuyContract();
            if (!string.IsNullOrWhiteSpace(id))
            {
                contract = _context.BuyContract.Include(p => p.DeviceType).Single(p => p.Id == id);
            }
            else //自动生成ID
            {
                contract.Id = System.Guid.NewGuid().ToString();
            }

            return View(Tuple.Create(typeList, contract));
        }


        /// <summary>
        /// 进入创建页面或者编辑页面
        /// </summary>
        public IActionResult Detail(String id)
        {
            //获取设备分类，用于下拉显示
            var typeList = _context.DeviceType.Where(p => p.Deleted == 0).OrderBy(p => p.SortOrder).ToList();

            //获取model
            BuyContract contract = new BuyContract();
            if (!string.IsNullOrWhiteSpace(id))
            {
                contract = _context.BuyContract.Include(p => p.DeviceType).Single(p => p.Id == id);
            }
            else //自动生成ID
            {
                contract.Id = System.Guid.NewGuid().ToString();
            }

            return View(Tuple.Create(typeList, contract));
        }

        [HttpPost]
        public AjaxResult Save(BuyContract obj,string deviceTypeId)
        {
            DeviceType type = _context.DeviceType.SingleOrDefault(p => p.Id == deviceTypeId);
            var exist = _context.BuyContract.Any(p=>p.Id == obj.Id);
            if (obj.Id == null || !exist){ //新增
                obj.CreateDate = DateTime.Now;
                obj.Deleted = 0;
                obj.DeviceType = type;
                _context.Add(obj);
                _context.SaveChanges();
                return AjaxResult.GetOK("保存成功");
            }
            else
            {
                BuyContract contract = _context.BuyContract.Single(p => p.Id == obj.Id);
                contract.BuyCount = obj.BuyCount;
                contract.BuyUser = obj.BuyUser;
                contract.StartDate = obj.StartDate;
                contract.Title = obj.Title;
                contract.Addr = obj.Addr;
                contract.Amount = obj.Amount;
                contract.Purpose = obj.Purpose;               
                contract.EndDate = obj.EndDate;
                contract.DeviceType = type;
                this._context.SaveChanges(); //保存
                return AjaxResult.GetOK("保存成功");
            }
        }       
 

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public AjaxResult Delete(string id)
        {
            AjaxResult result = new AjaxResult();
            if (id == null) return AjaxResult.GetError("删除失败！");

            result.Code = 1;
            var BuyContract = _context.BuyContract.FirstOrDefault(m => m.Id == id);
            if (BuyContract == null) return AjaxResult.GetError("未找到数据");

            BuyContract.Deleted = 1;
            _context.SaveChanges();
            return AjaxResult.GetOK("删除成功");
        }       
    }
}
